import co from "co";
let OSS = require("ali-oss");

const OSSConfig = {
  uploadHost: "https://pte0.oss-cn-beijing.aliyuncs.com", //OSS上传地址
  type: "scs",
  ossParams: {
    region: "oss-cn-beijing",
    accessKeyId: "LTAI5tDMrPGFgwcGymE26kTy",
    accessKeySecret: "rlvjzTegJvUAkkio69reXZcUM6jKJn",
    bucket: "pte0"
  }
};

function random_string(len) {
  len = len || 32;
  var chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";
  var maxPos = chars.length;
  var pwd = "";
  for (let i = 0; i < len; i++) {
    pwd += chars.charAt(Math.floor(Math.random() * maxPos));
  }
  return pwd;
}

/**
 *
 * @param event 上传图片的资源路径
 * @param type 图片资源类型
 * @param dir oss要保存的文件夹
 * @returns {OSS文件路径}
 */

function uploadOSS(event, dir) {
  return new Promise((resolve, reject) => {
    var client = new OSS({
      region: OSSConfig.ossParams.region,
      accessKeyId: OSSConfig.ossParams.accessKeyId,
      accessKeySecret: OSSConfig.ossParams.accessKeySecret,
      bucket: OSSConfig.ossParams.bucket
    });
    var file;

    file = event;
    let randomName = "easton/" + dir + '/'+`${random_string(6)}_${file.name}`;


    co(function*() {
      var result = yield client.multipartUpload(randomName, file);
    //   console.log(`${OSSConfig.uploadHost}/${result.name}`);
      resolve(`${OSSConfig.uploadHost}/${result.name}`);
    }).catch(function(err) {
      console.log(err);
      reject(err);
    });
  });
}

export { uploadOSS };
